let plugin = requirePlugin("live-room");
let app = getApp();
import utils from '../../utils/util';
let authLogin = function (params, headerToken) {
  return new Promise((resolve, reject) => {
    let envConfig = wx.getStorageSync('envConfig');
    wx.request({
      url: envConfig.apiUrl + 'liveApplet/authLogin',
      data: params,
      dataType: "json",
      header: {
        'Authorization': 'Bearer ' + headerToken,
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: "POST",
      success: function (res) {
        //token 存在 还返回1002，这个时候就要强制
        if (res.data.statusCode == 200) {
          resolve(res.data.data);
        } else if (res.data.msg == "未找到该用户" || res.data.statusCode == 402 || res.data.statusCode == 500 || res.data.statusCode == 403 || res.data.status == 403) {
          wx.removeStorage("roomToken");
          wx.removeStorage("shopInfo")
          wx.redirectTo({
            url: '/pages/auth-user/index'
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none"
          });
        }
      },
      fail: function (res) {
        console.warn("HttpRequst当中wx.request fail 执行了：调用失败", res);
        reject();
      },
      complete: function (res) {
        console.log(res);
      }
    })
  })
}

let asyncLogin = function () {
  return new Promise((resolve, reject) => {
    wx.login({
      success(res) {
        if (res.code) {
          let envConfig = wx.getStorageSync('envConfig');
          wx.request({
            url: envConfig.apiUrl + 'liveApplet/authByCode',
            data: {
              code: res.code
            },
            dataType: "json",
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            method: "POST",
            success: function (res) {
              console.log("wx.login-token:", res)
              if (res.data.data.openId) {
                wx.setStorageSync("userSecret", {
                  openId: res.data.data.openId,
                  sessionKey: res.data.data.sessionKey,
                  unionId: res.data.data.unionId
                });
                resolve(res.data.data)
              }
            },
            fail: function (res) {
              console.warn("wxLogin当中wx.request fail 执行了：调用失败")
              reject();
            }
          })
        } else {
          console.warn('登录失败！' + res.errMsg)
        }
      },
      fail: function () {
        console.warn("调用wx.login接口失败！")
      }
    })
  })
}

let addSocialRoom = function (params, token) {
  return new Promise((resolve, reject) => {
    let envConfig = wx.getStorageSync('envConfig');
    wx.request({
      url: envConfig.apiUrl + 'social/addSocialRoom',
      data: params,
      dataType: "json",
      header: {
        'Authorization': 'Bearer ' + token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: "POST",
      success: function (res) {
        resolve()
      },
      fail: function (res) {
        reject();
      }
    })
  })
}
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    console.log("options", options)
    this._opts = options;
    plugin.setEnvConfig(options.env);
    utils.setEnvConfig(options.env);
    if (options.from == 'gzh' || options.from == 'lvApp') {
      await addSocialRoom({
        isCombos: 0,
        socialRoomId: options.socialRoomId
      }, options.token)
      let userSecret = wx.getStorageSync("userSecret");
      let sendData = {
        liveId: options.liveId
      }
      if (!options.detailId || options.detailId == 'undefined') {
        sendData.moduleType = 1;
      } else {
        sendData.moduleType = 2;
        sendData.detailId = options.detailId;
      }
      if (userSecret) {
        sendData.openId = userSecret.openId;
        authLogin(sendData, options.token).then(resLogin => {
          if (app.globalData.isCK) {
            wx.setStorageSync('token', resLogin.loginToken);
            wx.setStorageSync('shopInfo', resLogin.companyInfo);
          }
          this.getSystemInfo().then((res) => {
            plugin.setStorage("systemInfo", res);
            plugin.setStorage("userSecret", wx.getStorageSync('userSecret'));
            plugin.setStorage("roomToken", resLogin.companyInfo.apiToken).then(() => {
              this.jump(options);
            })
          })
        });
      } else {
        asyncLogin().then(res => {
          sendData.openId = res.openId;
          authLogin(sendData, options.token).then(resLogin => {
            if (app.globalData.isCK) {
              wx.setStorageSync('token', resLogin.loginToken);
              wx.setStorageSync('shopInfo', resLogin.companyInfo);
            }
            this.getSystemInfo().then((res) => {
              plugin.setStorage("systemInfo", res);
              plugin.setStorage("roomToken", resLogin.companyInfo.apiToken).then(() => {
                this.jump(options);
              })
            })
          })
        })
      }
    } else {
      this.getSystemInfo().then((res) => {
        plugin.setStorage("systemInfo", res);
        plugin.setStorage("userSecret", wx.getStorageSync("userSecret"));
        plugin.setStorage("roomToken", options.token).then(() => {
          this.jump(options);
        })
      })
    }
  },

  getSystemInfo() {
    return new Promise(resolve => {
      let systemInfo = wx.getStorageSync("systemInfo");
      console.log("systemInfo", systemInfo);
      if (!systemInfo) {
        wx.getSystemInfoSync({
          success: (res) => {
            let systemInfo = res;
            let navBarHeight = 0;
            if (/iphone\s{0,}x/i.test(systemInfo.model)) {
              navBarHeight = 88
            } else if (systemInfo.system.indexOf('Android') !== -1) {
              navBarHeight = 68
            } else {
              navBarHeight = 64
            }
            let menuButtonInfo = wx.getMenuButtonBoundingClientRect();
            systemInfo.menuButtonInfo = menuButtonInfo;
            systemInfo.navBarHeight = navBarHeight;
            systemInfo.menuRight = systemInfo.screenWidth - menuButtonInfo.right;
            systemInfo.menuBottom = menuButtonInfo.top - systemInfo.statusBarHeight;
            systemInfo.menuHeight = menuButtonInfo.height;
            systemInfo.menuWidth = menuButtonInfo.width;
            systemInfo.menuTop = menuButtonInfo.top;
            resolve(systemInfo);
          }
        })
      } else {
        resolve(systemInfo);
      }
    })
  },
  jump(options) {
    let url = `plugin://live-room/live-room?liveId=${options.liveId}&socialRoomId=${options.socialRoomId}`;
    if (options.detailId) {
      url += `&detailId=${options.detailId}`;
    }
    if (options.relateId) {
      url += `&relateId=${options.relateId}`;
    }
    wx.navigateTo({
      url: url,
      success: () => {
        this._opts = null;
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (!this._opts) {
      let currentPages = getCurrentPages();
      if (currentPages.length == 1) {
        //第三方引用的时候返回到这个页面直接跳转首页
        wx.redirectTo({
          url: '/pages/index/index'
        })
      } else {
        wx.navigateBack();
      }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})